﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Indigo.Quibbler.Data;
using System.Windows.Media.Animation;
using System.Timers;
using System.Windows.Threading;
using System.Threading;

namespace Indigo.Quibbler.Controls
{
    /// <summary>
    /// Interaction logic for ArticleGalleryControl.xaml
    /// </summary>
    public partial class ArticleGalleryControl : UserControl
    {
        #region Private Variable

        private System.Timers.Timer _timer = new System.Timers.Timer(5000);
        private bool _isAutoHide = false;
        private bool _isHidden = false;

        #endregion

        #region Properties
        public List<NewsArticle> ItemSource
        {
            get { return (List<NewsArticle>)GetValue(ItemSourceProperty); }
            set
            {
                SetValue(ItemSourceProperty, value);
            }
        }
        public int SelectedIndex
        {
            get { return (int)GetValue(SelectedIndexProperty); }
            set
            {
                SetValue(SelectedIndexProperty, value);
            }
        }
        public ZoomLevel Zoom
        {
            get { return (ZoomLevel)GetValue(ZoomProperty); }
            set { SetValue(ZoomProperty, value); }
        }
        #endregion

        #region Dependency Property
        public static readonly DependencyProperty ItemSourceProperty = DependencyProperty.Register("ItemSource", typeof(List<NewsArticle>), typeof(ArticleGalleryControl), new PropertyMetadata(OnItemSourceChanged));
        public static readonly DependencyProperty SelectedIndexProperty = DependencyProperty.Register("SelectedIndex", typeof(int), typeof(ArticleGalleryControl), new PropertyMetadata(0, OnSelectedIndexChanged));
        public static readonly DependencyProperty ZoomProperty =
            DependencyProperty.Register("Zoom", typeof(ZoomLevel), typeof(ArticleGalleryControl), new UIPropertyMetadata(ZoomLevel.Medium, OnZoomLevelChanged));
        #endregion

        #region Delegate
        public delegate void ArticleSelectionChangedEventHandler(object sender, int index);
        #endregion

        #region Public Events
        public event EventHandler Close;
        public event ArticleSelectionChangedEventHandler SelectionChanged;
        #endregion

        #region Public Members
        public void SpeakAloud()
        {
            try
            {
                this.mainReader.SpeakAloud();
            }
            catch
            {
                MessageBox.Show("Error in reading text. Sorry for the inconvenience");
            }
        }

        public void StopSpeaking()
        {
            try
            {
                this.mainReader.StopSpeaking();
            }
            catch { }
        }

        public void Scribble()
        {
            try
            {
                this.mainReader.Scribble();
            }
            catch { }
        }

        public void AddFeedback()
        {
            try
            {
                this.mainReader.AddFeedback();
            }
            catch { }
        }

        #endregion

        #region Ctor
        public ArticleGalleryControl()
        {
            this.InitializeComponent();
            listBox.SelectionChanged += new SelectionChangedEventHandler(listBox_SelectionChanged);
            mainReader.Close += new EventHandler(_ArticleGalleryCloseEventHandler);
            btnAutoHideBar.Click += new RoutedEventHandler(_ArticlAutoHideToggle);
            btnShowToolbarBar.MouseEnter += new MouseEventHandler(_ArticleListShowMouseEnter);
            listBox.MouseLeave += new MouseEventHandler(btnShowToolbarBar_MouseLeave);
            _timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);
            (this.Resources["sbShowArticle"] as Storyboard).Completed += new EventHandler(_AnimationShowCompleted);
            (this.Resources["sbHideArticle"] as Storyboard).Completed += new EventHandler(_AnimationHideCompleted);
        }



        #endregion

        #region Event Handlers
        void _ArticleListShowMouseEnter(object sender, MouseEventArgs e)
        {
            if (_isHidden)
            {
                _BeginAnimation("sbShowArticle");

            }
        }

        void _AnimationShowCompleted(object sender, EventArgs e)
        {

        }

        void btnShowToolbarBar_MouseLeave(object sender, MouseEventArgs e)
        {
            _isHidden = false;
        }

        void _AnimationHideCompleted(object sender, EventArgs e)
        {
            _isHidden = true;
        }

        void _timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            if (!_isHidden)
            {
                this.Dispatcher.Invoke(DispatcherPriority.Normal, (ThreadStart)delegate
                {
                    _BeginAnimation("sbHideArticle");
                });
            }
        }


        void _ArticlAutoHideToggle(object sender, RoutedEventArgs e)
        {
            _isAutoHide = !_isAutoHide;
            _timer.Enabled = _isAutoHide;
            if (_isAutoHide)
            {
                btnAutoHideBar.ToolTip = "Pin";
                System.Windows.Controls.Image imageControlAutoHide = (System.Windows.Controls.Image)VisualTreeHelper.GetChild(btnAutoHideBar, 0);
                imageControlAutoHide.Source = new BitmapImage(new Uri("pack://application:,,/Quibbler - Universal News Reader;component/Images/IconAutoHideEnabled.png", UriKind.RelativeOrAbsolute));
            }
            else
            {
                btnAutoHideBar.ToolTip = "Unpin";
                System.Windows.Controls.Image imageControlAutoHide = (System.Windows.Controls.Image)VisualTreeHelper.GetChild(btnAutoHideBar, 0);
                imageControlAutoHide.Source = new BitmapImage(new Uri("pack://application:,,/Quibbler - Universal News Reader;component/Images/IconAutoHideDisabled.png", UriKind.RelativeOrAbsolute));
            }
            if (_isAutoHide && !_isHidden)
            {
                _BeginAnimation("sbHideArticle");
            }
        }
        void _ArticleGalleryCloseEventHandler(object sender, EventArgs e)
        {
            if (Close != null)
                Close(this, e);
        }

        void listBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                mainReader.ItemSource = this.ItemSource[listBox.SelectedIndex];
                this.SelectedIndex = listBox.SelectedIndex;
                listBox.ScrollIntoView(listBox.SelectedItem);
                if (SelectionChanged != null)
                    SelectionChanged(this, this.SelectedIndex);
            }
            catch
            {
                //TODO: Set Not available image
            }
        }

        private void btnCloseClick(object sender, RoutedEventArgs e)
        {
            if (Close != null)
                Close(this, e);
        }
        #endregion

        #region Dependency Members

        private static void OnItemSourceChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
        {
            (obj as ArticleGalleryControl).OnItemSourceChanged(e);
        }

        private static void OnSelectedIndexChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
        {
            (obj as ArticleGalleryControl).OnSelectedIndexChanged(e);
        }

        private void OnSelectedIndexChanged(DependencyPropertyChangedEventArgs e)
        {
            try
            {
                if ((int)e.NewValue >= 0 && (int)e.NewValue <= ItemSource.Count - 1)
                    listBox.SelectedIndex = (int)e.NewValue;
                else
                    listBox.SelectedIndex = 0;

            }
            catch { }
        }

        private void OnItemSourceChanged(DependencyPropertyChangedEventArgs e)
        {
            try
            {
                List<NewsArticle> curValue = (List<NewsArticle>)e.NewValue;
                if (curValue == null || curValue.Count == 0)
                {
                    gridLayout.Visibility = Visibility.Collapsed;
                    gridNoContent.Visibility = Visibility.Visible;
                }
                else
                {
                    gridLayout.Visibility = Visibility.Visible;
                    gridNoContent.Visibility = Visibility.Collapsed;

                    listBox.ItemsSource = curValue;
                    if (SelectedIndex >= 0 && SelectedIndex <= ItemSource.Count - 1)
                        listBox.SelectedIndex = SelectedIndex;
                    else
                        listBox.SelectedIndex = 0;
                }
            }
            catch { }
        }

        private static void OnZoomLevelChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
        {
            (obj as ArticleGalleryControl).OnZoomLevelChanged(e);
        }

        private void OnZoomLevelChanged(DependencyPropertyChangedEventArgs e)
        {
            try
            {
                switch ((ZoomLevel)e.NewValue)
                {
                    case ZoomLevel.High: this.mainReader.ZoomLevel = 100;
                        break;
                    case ZoomLevel.Medium: this.mainReader.ZoomLevel = 80;
                        break;
                    case ZoomLevel.Low: this.mainReader.ZoomLevel = 70;
                        break;
                }
            }
            catch { }
        }


        #endregion

        #region Begin/Stop Animation
        private void _BeginAnimation(string storyboardKey)
        {
            try
            {
                Storyboard Animation = this.Resources[storyboardKey] as Storyboard;
                if (Animation != null)
                {
                    Animation.Begin();
                }
            }
            catch (Exception ex) { }
        }
        private void _StopAnimation(string storyboardKey)
        {
            try
            {
                Storyboard Animation = this.Resources[storyboardKey] as Storyboard;
                if (Animation != null)
                {
                    Animation.Stop();
                }
            }
            catch (Exception ex) { }
        }
        #endregion
    }

    public enum ZoomLevel { High, Medium, Low }
}
